package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;


    @RequiredPermission(name = "员工页面", expression = "employee:list")
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Model model) {
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        List<Department> departments = departmentService.selectDepartmentList();
        model.addAttribute("departments", departments);

        return "employee/list";
    }


    @RequestMapping("/delete")
    @RequiredPermission(name = "员工删除", expression = "employee:delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.deleteEmployee(id);
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("/deleteInBatches")
    @ResponseBody
    @RequiredPermission(name = "员工批量删除", expression = "employee:deleteInBatches")
    public void deleteInBatches(Long[] ids) {
        if (ids != null && ids.length != 0) {
            employeeService.deleteInBatches(ids);
        }
    }

    @RequestMapping("/input")
    @RequiredPermission(name = "员工新增或修改", expression = "employee:saveOrUpdate")
    public String input(Long id, Model model) {
        //获取所有部门的数据
        List<Department> departments = departmentService.selectDepartmentList();
        model.addAttribute("departments", departments);
        //获取所有角色的数据
        List<Role> roles = roleService.selectRoleList();
        model.addAttribute("roles", roles);
        if (id != null) {
            Employee employee = employeeService.selectEmployee(id);
            model.addAttribute("employee", employee);
        }
        return "employee/input";
    }


    /*因为我们使用表单插件 使用submit会进行验证 无法提交表单
     * 所以 我们要使用ajax来提交数据
     * 按钮类型是 button 要使用ajaxSubmit
     * 按钮类型是 submit 就使用ajaxFrom
     * */
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "员工新增或修改", expression = "employee:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (employee.getId() != null) {
                employeeService.updateEmpAndRole(employee, ids);
                jsonResult.setSuccess(true);
                jsonResult.setMsg("修改成功");

            } else {
                employeeService.saveEmpAndRole(employee, ids);
                jsonResult.setSuccess(true);
                jsonResult.setMsg("增加成功");
            }

        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("操作失败");
            e.printStackTrace();
        }
        return jsonResult;
    }

    //因为插件要求返回结果需要为键值对形式 key为valid  ，value为boolean类型
    //我们使用Map来封装
    @ResponseBody
    @RequestMapping("/checkUserName")
    public Map<String, Boolean> checkUserName(String username) {
        HashMap<String, Boolean> map = new HashMap<>();

        //通过请求过来的username 来查询用户名是否存在
        if (employeeService.checkUserName(username) == null) {
            map.put("valid", true);
        } else {
            map.put("valid", false);
        }
        return map;
    }

    @RequestMapping("/exportXls")
    @RequiredPermission(name = "员工数据下载", expression = "employee:exportXls")
    public void exportXls(HttpServletResponse response, String keyWord, Long deptId) throws IOException {
        //设置响应头
        // 就是设置文件名和后缀 如果没写 文件名就是路径名 和没有后缀 但是内容是一样的
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        //业务逻辑
        Workbook workbook = employeeService.exportXls(keyWord, deptId);

        //响应给浏览器
        workbook.write(response.getOutputStream());
    }

    @ResponseBody
    @RequestMapping("/importXls")
    @RequiredPermission(name = "员工数据上传", expression = "employee:importXls")
    public void importXls(MultipartFile file ,HttpSession session) throws IOException {
        List<String> list = employeeService.importXls(file);
        int last = list.size() -1;
        String lastOne = list.get(last);
        list.remove(last);
        session.setAttribute("msg",list);
        session.setAttribute("last",lastOne);
    }


    @RequestMapping("/updatePassword")
    @RequiredPermission(name = "密码修改", expression = "employee:updatePassword")
    @ResponseBody
    public JsonResult updatePassword(Long id, String password) {
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.updatePassword(id, password);
            jsonResult.setSuccess(true);
            jsonResult.setMsg("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMsg("修改失败");
        }
        return jsonResult;
    }

    @RequestMapping("/change")
    public String change(Long id) {
        employeeService.updateStatus(id);
        return "redirect:/employee/list";
    }

}


